package com.lanou3g.code0517;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet(name = "CookieServlet03", urlPatterns = "/cookie03")
public class CookieServlet03 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/plain;charset=utf-8");
        //plain当文本去写
        //cookie可以设置存活时间
        //URL编码,解决了cookie不能存储中文的问题
        String val = URLEncoder.encode("中文", "utf-8");
        Cookie cookie = new Cookie("cookie03", val);
        //存活时间的单位是秒
        cookie.setMaxAge(20);
        /*
        maxAge>0,表示cookie存活多少秒,到时间浏览器自动删除该cookie
        maxAge<0,表示无论设置成多少,都表示活到浏览器关闭,默认值是-1
        maxAge=0,表示告诉浏览器立即删除这个cookie
         */
        //让cookie可以在各个二级域名之间共享
        //cookie.setDomain("baidu.com");
        //设置二级域名
        /*
        www.baidu.com
        .com顶级域名
        baidu.com一级域名
        www.baidu.com二级域名
        pan.baidu.com二级域名
         */
        response.addCookie(cookie);
        PrintWriter writer = response.getWriter();
        for (Cookie c : request.getCookies()) {
            String name = c.getName();
            String value = c.getValue();
            writer.println(name + "::" + value);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
